<template>
  <view>
    <view class="page" v-if="isShow">
      <view class="background-wrap">
        <image class="bg-image" src="https://file.huishouka.com.cn/static/ic_real_bg.png" mode="aspectFill"/>
      </view>

      <image class="close-button" @tap="closePage" src="/static/images/ic_back.png" style="padding: 10rpx;"
             :style="{marginTop: statusBarHeight + 'px'}"></image>

      <!-- 认证信息卡片 -->
      <view class="card-list" :style="{marginTop: marginTop + 'px'}">
        <view class="card_container">
          <view class="card_left">
            <view style="font-size: 28rpx; color: black; font-weight: bold; margin-bottom: 15rpx;">个人认证
            </view>
            <view style="display: flex; font-size: 24rpx; margin-bottom: 10rpx;"
                  v-if="credentialLevel == 0">
              <view style="color: rgba(0, 0, 0, 0.60);">您还没初级认证，认证后可销卡和提现</view>
            </view>
            <view style="display: flex; font-size: 24rpx; margin-bottom: 10rpx;"
                  v-if="credentialLevel != 0">
              <view style="color: rgba(0, 0, 0, 0.60);">真实姓名：</view>
              <view style="color: black;">{{ realName }}</view>
            </view>
            <view style="display: flex; font-size: 24rpx; margin-bottom: 10rpx;"
                  v-if="credentialLevel != 0">
              <view style="color: rgba(0, 0, 0, 0.60);">证件号码：</view>
              <view style="color: black;">{{ idNum }}</view>
            </view>
            <view style="color: rgba(0, 0, 0, 0.36); font-size: 20rpx; margin-bottom: 10rpx;"
                  v-if="credentialLevel != 0">
              您当前已签署承诺书
            </view>
            <text
                style="color: #4D7EF4; font-size: 20rpx; border-bottom: 1rpx solid #4D7EF4; display: inline-block;"
                @click="viewContract()" v-if="credentialLevel != 0">查看电子合同
            </text>
          </view>
          <view class="card-right">
            <image v-if="credentialLevel == 2" style="height: 62rpx; width: 72rpx;"
                   src="/static/images/ic_real_sign.png"></image>
            <view @click="checkAuthStatus()" v-if="credentialLevel != 2"
                  style="padding: 4rpx 16rpx; background-color: #4D7EF4; border-radius: 8rpx; color: white; font-size: 24rpx;">
              {{ getButtonText() }}
            </view>
            <!-- <view @click="toSign" v-if="isReal && !isSign"
            style="padding: 4rpx 16rpx; background-color: #4D7EF4; border-radius: 8rpx; color: white; font-size: 24rpx">
            立即签署</view> -->
          </view>
        </view>

        <view class="card_container" style="margin-top: 40rpx;">
          <view class="card_left">
            <view style="font-size: 28rpx; color: black; font-weight: bold; margin-bottom: 15rpx;">企业认证
            </view>
            <!--            未认证 -->
            <view
                style="display: flex; flex-direction: column;font-size: 24rpx; margin-bottom: 10rpx; color: rgba(0, 0, 0, 0.60);"
                v-if="companyLevel == 0">
              <view>升级企业认证提升核销金额50万</view>
              <view>可独立配置核销费率</view>
            </view>
            <!--            认证失败-->
            <view style="font-size: 24rpx; margin-bottom: 10rpx; color: rgba(255, 0, 0, 0.6);" v-if="companyLevel == 3">
              失败原因：{{notes}}
            </view>
            <!--            已认证 审核中-->
            <view style="display: flex; font-size: 24rpx; margin-bottom: 10rpx;" v-if="companyLevel == 1 || companyLevel == 2">
              <view style="color: black;">{{ company }}</view>
            </view>
            <view style="display: flex; font-size: 24rpx; margin-bottom: 10rpx;" v-if="companyLevel == 1 || companyLevel == 2">
              <view style="color: black;">{{ regnum }}</view>
            </view>
            <text @click="viewCompanyContract()"
                  style="color: #4D7EF4; font-size: 20rpx; border-bottom: 1rpx solid #4D7EF4; display: inline-block;"
                  v-if="companyLevel == 2 && enterpriseContractStatus == 1">查看签署合同
            </text>
          </view>
          <view class="card-right">
            <view style="color: #3EB266; font-size: 28rpx; font-weight: 500;" v-if="companyLevel == 1">审核中</view>
            <view v-if="companyLevel == 0" @click="toCompanySign()"
                  style="padding: 4rpx 16rpx; background-color: #4D7EF4; border-radius: 8rpx; color: white; font-size: 24rpx;">
              开始认证
            </view>
            <view v-if="companyLevel == 3" @click="toCompanySign()"
                  style="padding: 4rpx 16rpx; background-color: #4D7EF4; border-radius: 8rpx; color: white; font-size: 24rpx;">
              重新认证
            </view>
            <view v-if="companyLevel == 2 && enterpriseContractStatus == 0" @click="gotoCompanySign()"
                  style="padding: 4rpx 16rpx; background-color: #4D7EF4; border-radius: 8rpx; color: white; font-size: 24rpx;">
              去签署
            </view>
            <image v-if="companyLevel == 2 && enterpriseContractStatus == 1" style="height: 62rpx; width: 72rpx;"
                   src="/static/images/ic_company_sign.png"></image>
          </view>
        </view>
      </view>

      <uni-popup ref="cameraPopup" type="top">
        <view class="popup-content">
          <view class="title">相机权限说明</view>
          <view class="content">用于拍照上传个人身份信息进行实名认证</view>
        </view>
      </uni-popup>

      <uni-popup ref="galleryPopup" type="top">
        <view class="popup-content">
          <view class="title">相册权限说明</view>
          <view class="content">用于从相册上传个人身份信息进行实名认证</view>
        </view>
      </uni-popup>

      <u-popup :show="showAuthPopup" @close="closeAuthPop()" round="36rpx" mode="center"
               :closeOnClickOverlay="false" :safeAreaInsetBottom="false">
        <view class="popup-auth-container">
          <view
              style="text-align: center; margin-top: 30rpx; font-size: 32rpx; color: black; font-weight: 500;">
            实名认证
          </view>
          <view class="auth-input-container" style="margin-top: 38rpx;">
            <input class="auth-input" placeholder="与身份证一致的真实姓名" placeholder-class="ph-style"
                   v-model="authName"/>
          </view>
          <view class="auth-line"></view>
          <view class="auth-input-container">
            <input class="auth-input" placeholder="身份证号" placeholder-class="ph-style" v-model="authId"/>
          </view>
          <view class="auth-line"></view>
          <view class="auth-hint-container">
            <image style="width: 23rpx; height: 21rpx;" src="/static/images/ic_sale-pop.png"></image>
            请输入与您银行卡、微信、支付宝一致的姓名和身份证号
          </view>

          <view class="auth-line" style="margin-top: 20rpx; margin-left: 0; margin-right: 0;"></view>

          <view class="auth-button-container">
            <view class="auth-button" @click="closeAuthPop">取消</view>
            <view style="height: 100%; width: 2rpx; background-color: rgba(0, 0, 0, 0.12);"></view>
            <view class="auth-button" @click="toSign">立即认证</view>
          </view>
        </view>
      </u-popup>
    </view>
  </view>
</template>

<script>
export default {
  onShow() {
    this.loadUserData()
  },
  created() {
    // 获取系统信息
    const systemInfo = uni.getSystemInfoSync()
    //获取状态栏高度
    this.statusBarHeight = systemInfo.statusBarHeight
    this.marginTop = 125 - this.statusBarHeight;

    // 微信小程序适配
    // #ifdef MP-WEIXIN
    const menuRect = uni.getMenuButtonBoundingClientRect()
    this.rightSafeArea = systemInfo.windowWidth - menuRect.left // 计算右侧避让距离
    // #endif
  },
  data() {
    return {
      realName: '',
      idNum: '',
      statusBarHeight: 20,
      marginTop: 0,
      credentialLevel: 0,
      showAuthPopup: false,
      authName: '',
      authId: '',
      isShow: uni.getStorageSync("isShow"),
      companyLevel: 0,//0 未提交，1-待审核，2-通过，3-拒绝
      enterpriseContractStatus: 0,//0-未签署；1-已签署
      notes: '',
      company: '',
      regnum: '',
      imgData: '',
    }
  },
  methods: {
    // 关闭页面逻辑
    closePage() {
      uni.navigateBack();
    },
    //更新用户信息
    async loadUserData() {
      const res = await this.$http({
        method: 'GET',
        url: '/user/base/info',
      });
      const user = res.data;
      this.$app.setUserInfo(user);

      if (user) {
        this.realName = user.name;
        this.idNum = user.idNum;
        this.credentialLevel = user.credentialLevel;
        this.companyLevel = user.enterpriseStatus;
        this.enterpriseContractStatus = user.enterpriseContractStatus;
        this.notes = user.notes ? user.notes : "请联系客服";
        this.company = user.company;
        this.regnum = user.regnum;
      }
    },
    /**
     * 支付宝小程序 base64 图片转本地路径
     */
    async base64ToPath(base64Data) {
      // 推荐使用支付宝小程序官方的用户数据目录
      const fs = my.getFileSystemManager();
      const base64 = base64Data.replace(/^data:image\/\w+;base64,/, "");
      // 生成一个唯一的文件名
      const fileName = `${my.env.USER_DATA_PATH}/${Date.now()}.png`;
      try {
        fs.writeFileSync({
          filePath: fileName,
          data: base64,
          encoding: 'base64'
        });
        return fileName;
      } catch (e) {
        console.error('base64ToPath error:', e);
        return '';
      }
    },
    // 查看合同
    async viewContract() {
      try {
        const res = await this.$http({
          method: 'GET',
          url: '/user/contract/img',
        });
        const base64Data = 'data:image/png;base64,' + res.data;
        // #ifdef MP-ALIPAY
        const path = await this.base64ToPath(base64Data);
        if (path) {
          uni.previewImage({
            urls: [path]
          });
        } else {
          uni.showToast({ title: '图片显示失败', icon: 'none' });
        }
        // #endif
        // #ifndef MP-ALIPAY
        uni.previewImage({
          urls: [base64Data]
        });
        // #endif
      } catch (error) {
        console.log(error);
      }
    },
    async viewCompanyContract() {
      const res = await this.$http({
        method: 'GET',
        url: '/user/enterprise/info',
      });
      if (res && res.data.contractImg){
        const base64Data = 'data:image/png;base64,' + res.data.contractImg;
        // #ifdef MP-ALIPAY
        const path = await this.base64ToPath(base64Data);
        if (path) {
          uni.previewImage({
            urls: [path]
          });
        } else {
          uni.showToast({ title: '图片显示失败', icon: 'none' });
        }
        // #endif
        // #ifndef MP-ALIPAY
        uni.previewImage({
          urls: [base64Data]
        });
        // #endif
      }

    },
    // 去实名
    async toRealName() {
      // this.$app.openUrl("https://m.huishouka.com.cn/bd?token=v3P9WhnpSA9affdNqkDJtW0N&callbackUrl=http://face.shengniudinggou.com:8083?token=v3P9WhnpSA9affdNqkDJtW0N")
      // let platform = uni.getSystemInfoSync().platform;//​​设备底层平台标识​​
      // let uniPlatform = uni.getSystemInfoSync().uniPlatform;
      // console.log("当前平台是", platform)//android devtools ios windows
      // console.log("当前运行环境是", uniPlatform)//app mp-weixin web
      // if (platform == "android") {
      // 	if (plus.navigator.checkPermission('android.permission.CAMERA') === 'authorized' && plus
      // 		.navigator
      // 		.checkPermission('android.permission.READ_EXTERNAL_STORAGE') === 'authorized') {
      // 		// 已经获得相机和相册权限
      // 		// 执行业务代码
      // 		const res = await this.$http({
      // 			method: 'GET',
      // 			url: '/user/face/print'
      // 		})
      // 		if (res && res.data) {
      // 			this.$app.openUrl(res.data, false)
      // 		}
      // 	} else {
      // 		// 其中一个权限未取得或被拒绝
      // 		this.getAndroidCameraPermission()
      // 	}
      // } else {
      // 	const res = await this.$http({
      // 		method: 'GET',
      // 		url: '/user/face/print'
      // 	})
      // 	if (res && res.data) {
      // 		// window.location.href = res.data
      // 		this.$app.openUrl(res.data, false)
      // 	}
      // }

      const res = await this.$http({
        method: 'GET',
        url: '/user/face/print'
      })
      if (res && res.data) {
        // window.location.href = res.data
        this.$app.openUrl(res.data, false)
      }
    },
    // 获得安卓相机权限
    getAndroidCameraPermission() {
      this.$refs.cameraPopup.open();
      plus.android.requestPermissions(['android.permission.CAMERA',], (e) => {
        this.$refs.cameraPopup.close();
        if (e.deniedAlways.length > 0) { //权限被永久拒绝
          // 弹出提示框解释为何需要权限，引导用户打开设置页面开启
          guideUserToAuthorize('请打开手机相机功能（点击确定后在权限中授权相机功能）')
        } else if (e.deniedPresent.length > 0) { //权限被临时拒绝
          // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
          guideUserToAuthorize('请打开手机相机功能（点击确定后在权限中授权相机功能）')
        } else {
          this.$refs.galleryPopup.open();
          plus.android.requestPermissions(['android.permission.READ_EXTERNAL_STORAGE'], async (
              e) => {
            this.$refs.galleryPopup.close();
            if (e.deniedAlways.length > 0) { //权限被永久拒绝
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启
              guideUserToAuthorize('请打开相册存储功能（点击确定后在权限中授权相册存储功能）')
            } else if (e.deniedPresent.length > 0) { //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
              guideUserToAuthorize('请打开相册存储功能（点击确定后在权限中授权相册存储功能）')
            } else {
              // 执行业务代码
              const res = await this.$http({
                method: 'GET',
                url: '/user/face/print'
              })
              if (res && res.data) {
                this.$app.openUrl(res.data, false)
              }
            }
          })
        }
      })
    },
    // 去签署
    async toSign() {
      if (!this.authName) {
        uni.showToast({
          title: '姓名不能为空',
          position: 'bottom',
          icon: 'none'
        });
        return false;
      }

      if (!this.authId) {
        uni.showToast({
          title: '身份证号不能为空',
          position: 'bottom',
          icon: 'none'
        });
        return false;
      }

      try {
        const res = await this.$http({
          method: 'GET',
          url: '/user/contract/signUrl',
          data: {
            name: this.authName,
            idNum: this.authId,
          },
        })
        if (res && res.data) {
          this.closeAuthPop();
          // uni.$u.toast(res.data);
          this.$app.openUrl(res.data, false)
        }
      } catch (error) {
        uni.$u.toast(error);
      }
    },
    // 获取按钮内容
    getButtonText() {
      console.log("认证等级", this.credentialLevel)
      if (this.credentialLevel == 0) {
        return "开始初级认证";
      } else {
        return "开始高级认证";
      }
    },
    checkAuthStatus() {
      if (this.credentialLevel == 0) {
        this.showAuthPop();
      } else {
        this.toRealName();
      }
    },
    showAuthPop() {
      this.showAuthPopup = true;
    },
    closeAuthPop() {
      this.showAuthPopup = false;
    },
    // 去企业认证
    toCompanySign() {
      if (this.credentialLevel != 2) {
        uni.showToast({
          title: '请先完成高级认证',
          position: 'bottom',
          icon: 'none'
        });
        return;
      }
      uni.navigateTo({
        url: `/pages/company-auth/company-auth`
      });
    },
    //   去签署企业合同
    async gotoCompanySign() {
      const res = await this.$http({
        method: 'GET',
        url: '/user/contract/enterprise/signUrl',
      })
      if (res && res.data) {
        this.$app.openUrl(res.data, false)
      }
    },
  }
};
</script>

<style scoped lang="scss">
.page {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.close-button {
  width: 50rpx;
  height: 50rpx;
  margin-left: 24rpx;
}

/* 背景图容器 */
.background-wrap {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 320rpx;
  /* 控制背景图高度为 Banner 的一半 */
  z-index: 0;
  /* 确保背景图在 Banner 下方 */

  .bg-image {
    width: 100%;
    height: 100%;
  }
}

.card-list {
  height: 100%;
  background-color: #fff;
  border-top-left-radius: 50rpx;
  border-top-right-radius: 50rpx;
  padding: 56rpx 30rpx;
}

.card_container {
  padding-left: 52rpx;
  padding-right: 52rpx;
  padding-top: 30rpx;
  padding-bottom: 12rpx;
  display: flex;
  justify-content: space-between;
  border-radius: 8rpx;
  box-shadow: 0rpx 4rpx 16rpx 0rpx rgba(162, 162, 162, 0.5);
}

.card-right {
  display: flex;
  align-items: center;
}

// 权限说明弹窗
.popup-content {
  position: relative;
  z-index: 2000;
  background-color: #eee;
  width: 90%;
  margin: 0 auto;
  margin-top: 10vh;
  padding: 32rpx;
  border-radius: 32rpx;
  color: #000;
  // 阴影
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.3);

  .title {
    font-size: 32rpx;
    font-weight: bold;
  }

  .content {
    margin-top: 16rpx;
    line-height: 1.5;
  }
}

//认证弹窗
.popup-auth-container {
  width: 590rpx;
  display: flex;
  flex-direction: column;
}

.auth-input-container {
  padding: 28rpx 32rpx;
}

.auth-input {
  font-size: 28rpx;
}

.ph-style {
  color: rgba(0, 0, 0, 0.40);
}

.auth-hint-container {
  margin: 14rpx 24rpx;
  padding: 10rpx 6rpx;
  background-color: #FFFBE8;
  font-size: 20rpx;
  color: #ED6A0C;
}

.auth-line {
  height: 2rpx;
  margin: 0 32rpx;
  background-color: rgba(0, 0, 0, 0.12);
}

.auth-button-container {
  display: flex;

  .auth-button {
    flex: 1;
    padding: 26rpx 0;
    text-align: center;
    color: rgba(0, 0, 0, 0.85);
    font-size: 32rpx;
  }
}
</style>